package edu.washington.cs.pomdb;

import java.util.ArrayList;
import java.util.Random;

import edu.washington.cs.pomdb.ExpCtrl.*;
import edu.washington.cs.pomdb.gui.GUI;

/**
 * @author Yanping Huang
 *
 */
public class Trial {
	double totalReward;
	int trialID;
	double coherence;
	Actions answer;
	boolean isCorrect;
	boolean isFinished;
	int reactionTime;
	ArrayList<Observations> beadSequence;
	double R_P;
	double R_N;
	double R_W;
	String userName;
	Random r;
	/**
	 * 
	 */
	public Trial(String userName){
		this.userName = userName;
		r = new Random();
		beadSequence = new ArrayList<Observations>();
		//TODO get serial id for trialID
  		//TODO initialized coherence
		coherence = r.nextDouble();
 		totalReward = -1;
 		R_P = Rewards.R_P.getReward();
 		R_N = Rewards.R_N.getReward();
 		R_W = Rewards.R_W.getReward();

	}
	
	public boolean isFinished(){
		return isFinished;
	}
	
	public void start(){
		while(!nextObservation());
	}
	
	public void setTotalReward(double r){
		totalReward = r;
	}
	public void setCohrence(double c){
		coherence = c;
	}
	public void setRewards(double rp, double rn, double rw){
		R_P  = rp;
		R_N = rn;
		R_W = rw;
	}
	
	public void setReactionTime(int t){
		reactionTime = t;
	}
	
	public void setIsFinished(boolean b){
		isFinished = b;
	}
	
	public void setAnswer(Actions a){
		answer = a;
	}
	
	public void setIsCorrect(boolean b){
		isCorrect = b;
	}
	
	void terminateTrial(Actions a){
		answer = a;
		isFinished = true;
		reactionTime = beadSequence.size();
		if(coherence > 0 ){
			isCorrect = (a == Actions.A_R);
		}else if(coherence < 0){
			isCorrect = (a == Actions.A_L);
		}
		else{
			double p = r.nextDouble();
			if (p > 0.5)
				isCorrect = true;
			else
				isCorrect = false;
		}
		if(isCorrect)
			totalReward += R_P;
		else
			totalReward += R_N;
	}
	
	
	boolean nextObservation(){
		Observations newBead;
		double p = r.nextDouble();
		if( p <= (coherence + 1) / 2)
			newBead = Observations.O_R;
		else
			newBead = Observations.O_L;
		Actions a = GUI.showObservation(newBead, userName, totalReward);
		beadSequence.add(newBead);
		switch(a){
		case A_L:
			terminateTrial(a);
			break;
		case A_R:
			terminateTrial(a);
			break;
		case A_W:
			isFinished = false;
			totalReward += R_W;
			break;			
		}
		return isFinished;
	}
	
	public String toString() {
		return "Coherence=" + coherence + "\tR_p=" + R_P
		       + "\tR_n=" + R_N + "\tR_W=" + R_W
		       + "\tDirection=" + answer + "\t ReacTime=" + reactionTime
		       + "\tisCorrect=" + isCorrect 
		       + "\tReward=" + totalReward + "\n";
	}
	
}
